package com.legendframework.core.dao.transaction;

/**
 * 抽象的事务控制层
 */
public abstract class AbstractTransaction<T> implements ITransaction {

    protected ThreadLocal<T> threadLocal;

    public AbstractTransaction() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 获取当前线程的变量
     * @return
     */
    public T getThreadLocalData(){
        return threadLocal.get();
    }

    /**
     * 校验线程变量中的参数
     * @return
     */
    protected abstract boolean check();

    /**
     * 事务开始
     */
    protected abstract void start();

    /**
     * 事务提交
     */
    protected abstract void commit();

    /**
     * 事务回滚
     */
    protected abstract void back();

    @Override
    public void onStart() {
        if (!check()) {
            return;
        }
        start();
    }

    @Override
    public void onCommit() {
        if (!check()) {
            return;
        }
        commit();
    }

    @Override
    public void onBack() {
        if (!check()) {
            return;
        }
        back();
    }
}
